/* eslint-disable no-underscore-dangle */
const { knex } = require('../models');


class DbService {
  constructor(tableName) {
    this.tableName = tableName;
    this.knex = knex;
  }

  async getById(id) {
    return this.first({ id });
  }

  first(where) {
    return knex(this.tableName).where(where)
      .first();
  }

  selectBy({ where, offset, limit }) {
    return knex.select().from(this.tableName)
      .where(where)
      .offset(offset || 0)
      .limit(limit || 10);
  }

  selectAll(where = {}) {
    return knex.select().from(this.tableName)
      .where(where);
  }

  updateById(id, data) {
    return knex(this.tableName).where({ id })
      .update(data);
  }

  updateByWhere({
    data,
    where,
  }) {
    return knex(this.tableName).where(where || {})
      .update(data);
  }

  insert(data) {
    return knex(this.tableName).insert(data);
  }

  async upsert(data) {
    if (data.id) {
      const exist = await this.first({ id: data.id });
      if (exist) {
        return this.updateById(data.id, data);
      }
      return this.insert(data);
    }
  }

  deleteByWhere(where = {}) {
    return knex(this.tableName).where(where)
      .delete();
  }

  deleteById(id) {
    return knex(this.tableName).where({ id })
      .delete();
  }

  async countAll(where = {}) {
    const result = await knex(this.tableName).where(where)
      .count({ count: '*' });
    return result?.[0]?.count;
  }
}

module.exports = DbService;
